package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.Seat;
import com.example.domain.User;
import com.example.domain.Room;
import com.example.dto.SeatAddDTO;
import com.example.dto.SeatUpdateDTO;
import com.example.domain.StudyRoomReservation;
import com.example.exception.BusinessException;
import com.example.mapper.SeatMapper;
import com.example.mapper.UserMapper;
import com.example.mapper.RoomMapper;
import com.example.service.SeatService;
import com.example.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import com.example.service.StudyRoomReservationService;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.sql.Time;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @author HP
* @description 针对表【seat】的数据库操作Service实现
* @createDate 2025-08-18 19:33:19
*/

@Slf4j
@Service
public class SeatServiceImpl extends ServiceImpl<SeatMapper, Seat>
    implements SeatService {

    @Resource
    private SeatMapper seatMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private StudyRoomReservationService studyRoomReservationService;

    @Override
    public Result addSeat(SeatAddDTO seatAddDTO) {
        if (seatAddDTO == null) {
            throw new BusinessException("座位信息不能为空");
        }
        if (seatAddDTO.getStudyRoomId() == null) {
            throw new BusinessException("所属房间ID不能为空");
        }
        if (seatAddDTO.getNumber().trim().isEmpty()) {
            throw new BusinessException("座位编号不能为空");
        }
        // 检查房间是否存在
        Room room = roomMapper.selectById(seatAddDTO.getStudyRoomId());
        if (room == null) {
            throw new BusinessException("房间不存在");
        }

        // 检查座位号是否重复
        QueryWrapper<Seat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("study_room_id", seatAddDTO.getStudyRoomId());
        queryWrapper.eq("number", seatAddDTO.getNumber());
        Seat existingSeat = seatMapper.selectOne(queryWrapper);
        if (existingSeat != null) {
            throw new BusinessException("该房间已存在该座位号");
        }
        
        Seat seat = new Seat();
        BeanUtils.copyProperties(seatAddDTO, seat);
        int insert = seatMapper.insert(seat);
        if (insert <= 0) {
            throw new BusinessException("添加座位失败");
        }
        log.info("添加座位成功，seatId={}", seat.getId());
        return Result.success(seat.getId());
    }

    @Override
    public Result updateSeat(SeatUpdateDTO seatUpdateDTO) {
        if (seatUpdateDTO == null || seatUpdateDTO.getId() == null) {
            throw new BusinessException("座位ID不能为空");
        }

        // 检查座位是否存在
        Seat existingSeat = seatMapper.selectById(seatUpdateDTO.getId());
        if (existingSeat == null) {
            throw new BusinessException("座位不存在");
        }

        // 检查更新信息
        Room room = roomMapper.selectById(seatUpdateDTO.getStudyRoomId());
        if (room == null) {
            throw new BusinessException("房间不存在");
        }

        if (seatUpdateDTO.getNumber() != null && seatUpdateDTO.getNumber().trim().isEmpty()) {
            throw new BusinessException("座位编号不能为空");
        }

        // 如果修改了座位号，检查是否重复
        if (seatUpdateDTO.getNumber() != null && !seatUpdateDTO.getNumber().equals(existingSeat.getNumber())) {
            Long roomId = seatUpdateDTO.getStudyRoomId() != null ? seatUpdateDTO.getStudyRoomId() : existingSeat.getStudyRoomId();
            QueryWrapper<Seat> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("study_room_id", roomId);
            queryWrapper.eq("number", seatUpdateDTO.getNumber());
            queryWrapper.ne("id", seatUpdateDTO.getId());
            Seat duplicateSeat = seatMapper.selectOne(queryWrapper);
            if (duplicateSeat != null) {
                throw new BusinessException("该房间已存在该座位号");
            }
        }

        Seat seat = new Seat();
        BeanUtils.copyProperties(seatUpdateDTO, seat);

        int update = seatMapper.updateById(seat);
        if (update <= 0) {
            throw new BusinessException("更新座位信息失败");
        }
        return Result.success();
    }

    @Override
    public Result deleteSeat(Long id) {
        if (id == null) {
            throw new BusinessException("座位ID不能为空");
        }

        // 检查座位是否存在
        Seat seat = seatMapper.selectById(id);
        if (seat == null) {
            throw new BusinessException("座位不存在");
        }

        // 检查座位是否被预约
        if (seat.getSeatStatus() != 1) { // 1表示有空闲，不是空闲状态则无法删除
            throw new BusinessException("该座位已被预约，无法删除");
        }

        int delete = seatMapper.deleteById(id);
        if (delete <= 0) {
            throw new BusinessException("删除座位失败");
        }
        return Result.success();
    }

    @Override
    public Result getSeatsByRoomId(Long roomId) {
        if (roomId == null) {
            throw new BusinessException("房间ID不能为空");
        }

        // 检查房间是否存在
        Room room = roomMapper.selectById(roomId);
        if (room == null) {
            throw new BusinessException("房间不存在");
        }

        QueryWrapper<Seat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("study_room_id", roomId);
        queryWrapper.orderByAsc("number");
        List<Seat> seats = seatMapper.selectList(queryWrapper);
        return Result.success(Map.of("seats", seats));
    }

    @Override
    public Result getAvailableSeats(Long roomId) {
        if (roomId == null) {
            throw new BusinessException("房间ID不能为空");
        }

        // 检查房间是否存在
        Room room = roomMapper.selectById(roomId);
        if (room == null) {
            throw new BusinessException("房间不存在");
        }

        QueryWrapper<Seat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("study_room_id", roomId);
        queryWrapper.eq("seat_status", 1); // 1表示有空闲
        queryWrapper.orderByAsc("number"); // 座位编号排序
        List<Seat> seats = seatMapper.selectList(queryWrapper);

        return Result.success(Map.of("seats", seats));
    }

    @Override
    public List<Seat> getAvailableSeats() {
        QueryWrapper<Seat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("seat_status", 1); // 1表示有空闲
        queryWrapper.orderByAsc("study_room_id", "number"); // 使用实体类中的字段名
        List<Seat> seats = seatMapper.selectList(queryWrapper);
        return seats;
    }

    @Override
    public boolean reserveSeat(Long userId, Long seatId, Time startTime, Time endTime) {
        // 委托给StudyRoomReservationService处理预约业务逻辑
        return studyRoomReservationService.createReservation(userId, seatId, startTime, endTime);
    }

    @Override
    public boolean cancelReservation(Long reservationId) {
        if (reservationId == null) {
            throw new BusinessException("预约ID不能为空");
        }

        // 获取预约记录以获取用户ID
        StudyRoomReservation reservation = studyRoomReservationService.getById(reservationId);
        if (reservation == null) {
            throw new BusinessException("预约记录不存在");
        }

        // 委托给StudyRoomReservationService处理取消预约业务逻辑
        return studyRoomReservationService.cancelReservation(reservationId, reservation.getUserId(), 
                reservation.getUserId(), "用户取消", "127.0.0.1");
    }

    @Override
    public List<Seat> getUserReservations(Long userId) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }

        // 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 获取用户的预约记录
        List<StudyRoomReservation> reservations = studyRoomReservationService.getUserReservations(userId);
        
        // 根据预约记录获取对应的座位信息
        List<Seat> seats = new java.util.ArrayList<>();
        for (StudyRoomReservation reservation : reservations) {
            Seat seat = seatMapper.selectById(reservation.getSeatId());
            if (seat != null) {
                seats.add(seat);
            }
        }
        
        return seats;
    }
}




